<template>
  <el-card shadow="never" class="box">
    <template #header>
      <span class="title" style="font-size: 28px; font-weight: 700;">患者查看</span>
    </template>

    <!-- 1. 统计卡片 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card done">
          <div class="stat-number">{{ todayDone }}</div>
          <div class="stat-label">今日已看诊（人）</div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card queue">
          <div class="stat-number">{{ queueNow }}</div>
          <div class="stat-label">当前排队（人）</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 2. 搜索 -->
    <el-form :inline="true" :model="search" class="search-area">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input
            v-model="search.realName"
            placeholder="输入患者姓名搜索"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix><el-icon><Search /></el-icon></template>
          </el-input>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 3. 表格 -->
    <el-table :data="pageTable" stripe border>
      <el-table-column prop="index" label="编号" width="100" />
      <el-table-column prop="realName" label="患者姓名" />
      <el-table-column prop="id" label="病人ID号" />
      <!-- 新增身份证号列 -->
      <el-table-column prop="cardNumber" label="身份证号" min-width="180">
        <template #default="{ row }">
          <!-- 身份证号中间8位用*替换，保护隐私 -->
          {{ row.cardNumber ? row.cardNumber.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3') : '' }}
        </template>
      </el-table-column>
      <!-- 新增家庭地址列 -->
      <el-table-column prop="homeAddress" label="家庭地址" min-width="150" />
      <!-- 新增看诊时间列 -->
      <el-table-column label="看诊时间" min-width="150">
        <template #default="{ row }">
          {{ row.visitDate }} {{ row.noon }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350">
        <template #default="{ row }">
          <!-- <el-button size="small" :icon="Edit" @click="handleCreate(row)">创建病案</el-button>
          <el-button size="small" :icon="Right" @click="handleSkip(row)">跳过</el-button> -->
          <el-button size="small" type="primary" :icon="Phone" @click="handleCall(row)">叫号</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 4. 底部叫号 -->
    <!-- <div class="bottom-bar">
      <el-button type="primary" size="large" :disabled="!canCall" @click="handleCallNext">叫号</el-button>
    </div> -->

    <!-- 5. 分页 -->
    <el-pagination
      v-model:current-page="page.current"
      :page-size="page.size"
      :total="total"
      layout="prev, pager, next, jumper, ->, total"
      @current-change="handlePage"
      class="pagination"
    />
  </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Search, Edit, Right, Phone } from '@element-plus/icons-vue'
import { registerApi } from '@/api'
import patientApi from '@/api/patient'

// 路由相关
const router = useRouter()

/* ---------- 数据 ---------- */
const patientList = ref([])
const search = reactive({ realName: '' })
const page = reactive({ current: 1, size: 5 })
const total = ref(0)

/* 今日统计 & 排队 */
const todayDone = ref(0)
const queueNow = computed(() => patientList.value.filter(i => i.visitState === 1).length)

/* 能否叫号 */
const canCall = computed(() => patientList.value.some(i => i.visitState === 1))

/* ---------- 搜索 & 分页 ---------- */
const filterList = computed(() => {
  if (!search.realName) return patientList.value
  return patientList.value.filter(
    i => i.realName && i.realName.includes(search.realName)
  )
})

// 修改pageTable计算属性，去掉前端分页逻辑
const pageTable = computed(() => {
  // 直接使用过滤后的列表，不再进行前端切片
  return filterList.value.map((item, index) => ({
    ...item,
    // 计算正确的序号（基于后端返回的分页数据）
    index: (page.current - 1) * page.size + index + 1
  }))
})

// 同时确保getPatientList函数正确传递分页参数
async function getPatientList() {
  const loading = ElLoading.service({ text: '加载中...' })
  try {
    const params = {
      pageNum: page.current,  // 传给后端的页码
      pageSize: page.size,    // 传给后端的每页条数
      ...(search.realName ? { realName: search.realName } : {})
    }
    
    const res = await registerApi.getByPage(params)
    
    // 假设后端返回格式为 { list: [], total: 0 }
    patientList.value = res.list || []
    total.value = res.total || 0  // 使用后端返回的总条数
  } catch (error) {
    ElMessage.error(`获取患者列表失败：${error.message || '未知错误'}`)
    console.error('获取患者列表失败:', error)
  } finally {
    loading.close()
  }
}

// 获取今日统计数据
async function getTodayStatistics() {
  try {
    const res = await patientApi.getTodayStats()
    if (res.success && res.data) {
      todayDone.value = res.data.doneCount || 0
    } else {
      // 如果没有专门的统计接口，从列表中计算
      todayDone.value = patientList.value.filter(i => i.visitState === 3).length
    }
  } catch (error) {
    console.warn('获取统计数据失败，使用本地计算:', error)
    // 降级处理：从当前列表计算
    todayDone.value = patientList.value.filter(i => i.visitState === 3).length
  }
}

/* ---------- 操作 ---------- */
function handleSearch() {
  page.current = 1
  getPatientList()
}

function handlePage(newPage) {
  page.current = newPage
  getPatientList()
}

async function handleCreate(row) {
  try {
    const medicalRecordData = {
      registerId: row.id,
      patientName: row.realName,
      creationTime: new Date()
    }
    
    const res = await patientApi.createMedicalRecord(medicalRecordData)
    if (res.success) {
      ElMessage.success(`为 ${row.realName} 创建病案成功`)
      // 这里可以添加跳转到病历详情页的逻辑
    } else {
      ElMessage.error(`创建病案失败：${res.message || '未知错误'}`)
    }
  } catch (error) {
    ElMessage.error(`创建病案失败：${error.message || '未知错误'}`)
    console.error('创建病案失败:', error)
  }
}

async function handleSkip(row) {
  try {
    ElMessage.info(`已跳过 ${row.realName}`)
    // 实际项目中可能需要调用后端API来记录跳过操作
  } catch (error) {
    ElMessage.error(`跳过失败：${error.message || '未知错误'}`)
    console.error('跳过操作失败:', error)
  }
}

async function handleCall(row) {
  try {
    console.log('触发叫号操作，患者ID:', row.id)
    // 更新患者状态为看诊中
    const res = await registerApi.updateById(row.id, { visitState: 2 })
    console.log('API响应:', res)
    // 检查响应是否成功，根据API返回格式修改条件判断
    if (res.code === 200) {
      ElMessage.success(`正在叫号：${row.realName}`)
      console.log('叫号成功，准备刷新列表')
      // 刷新列表
      await getPatientList()
      await getTodayStatistics()
      
      console.log('准备使用router.push跳转，目标路径:', '/doctor/diagnosis', '患者ID:', row.id)
      // 使用Vue Router跳转
      router.push({
        path: '/doctor/diagnosis',
        query: { patientId: row.id }
      })
    } else {
      console.log('叫号失败，响应:', res)
      ElMessage.error(`叫号失败：${res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('叫号操作异常:', error)
    ElMessage.error(`叫号失败：${error.message || '未知错误'}`)
  }
}

function handleCallNext() {
  const next = patientList.value.find(i => i.visitState === 1)
  if (next) handleCall(next)
}

// 初始化加载数据
onMounted(async () => {
  await getPatientList()
  await getTodayStatistics()
})
</script>


<style lang="scss" scoped>
.box {
  padding: 0 20px 20px 20px;
}
.stat-row {
  margin-bottom: 20px;
}
.stat-card {
  text-align: center;
  border-radius: 8px;
  &.done {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    color: #fff;
  }
  &.queue {
    background: linear-gradient(135deg, #409eff 0%, #5da8ff 100%);
    color: #fff;
  }
  .stat-number {
    font-size: 32px;
    font-weight: 700;
  }
  .stat-label {
    font-size: 14px;
    margin-top: 4px;
  }
}
.search-area {
  margin-bottom: 20px;
}
.bottom-bar {
  position: sticky;
  bottom: 0;
  z-index: 10;
  background: #fff;
  padding: 16px 0;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e4e7ed;
}
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
</style>